package com.masterclient.app.businessmodule.settingmodule.crossborder;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.ReplacementTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.eoner.baselib.utils.status.StatusBarUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.managerlibrary.system.SystemConfigStorage;
import com.masterclient.app.R;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.base.CashTakePhotoDialog;
import com.eoner.baselibrary.widget.loading.ProgressDialog;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.businessmodule.settingmodule.auth.bean.CustomerOcrBean;
import com.masterclient.app.businessmodule.settingmodule.crossborder.contract.ManageCrossBorderContract;
import com.masterclient.app.businessmodule.settingmodule.crossborder.contract.ManageCrossBorderPresenter;
import com.masterclient.app.businessmodule.settingmodule.crossborder.model.CrossBorderListBean;
import com.masterclient.app.businessmodule.settingmodule.crossborder.model.NewCrossBorderUserMessage;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.megvii.demo.activity.IDCardDetectActivity;
import com.megvii.demo.utils.Configuration;
import com.megvii.idcardquality.IDCardQualityLicenseManager;
import com.megvii.licensemanager.Manager;
import com.suke.widget.SwitchButton;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(path = AroutePath.SETTING_UPLOAD_CROSS_BORDER_NAME)
public class UploadCrossBorderNameActivity extends FCBusinessActivity<ManageCrossBorderPresenter> implements ManageCrossBorderContract.View, TextWatcher {

    @BindView(R.id.card_id)
    EditText card_id;
    @BindView(R.id.name)
    EditText name;

    @BindView(R.id.id_img0)
    ImageView id_img0;
    @BindView(R.id.id_img1)
    ImageView id_img1;
    @BindView(R.id.tag0)
    View tag0;
    @BindView(R.id.tag1)
    View tag1;
    @BindView(R.id.next)
    TextView next;
    @BindView(R.id.re_front)
    TextView re_front;
    @BindView(R.id.re_back)
    TextView re_back;

    @BindView(R.id.reload)
    TextView reload;
    @BindView(R.id.reload_layout)
    View reload_layout;
    @BindView(R.id.id_image_layout)
    View id_image_layout;

    @BindView(R.id.switch_button)
    SwitchButton switchButton;


    public static final int IMAGE_PICKER = 102;
    public static final int REQUEST_CODE_SELECT = 100;

    RxPermissions rxPermissions;

    String amount = "";

    ProgressDialog progressDialog;

    private int source = 0;

    private static final int INTO_IDCARDSCAN_PAGE = 100;

    String id ,is_default = "0";
    String img_url0,img_url1;

    @Autowired(name = "bean")
    NewCrossBorderUserMessage crossBorderUserMessage;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.upload_cross_border_name;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("填写身份信息").setRightBtnText("查看示例");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        StatusBarUtil.setStatusBarColor(getActivity(), Color.parseColor("#FFFFFF"));
        init();
        addListener();
    }

    @Override
    protected void onNavigationRightClick() {
        startActivitry(BridgeActivity.class,new String[][]{{"url", SystemConfigStorage.getInstance().getOcrExampleUrl()},{"title","查看示例"}});
    }

    private void init() {
        source = getIntent().getIntExtra("source",0);
        rxPermissions = new RxPermissions(this);

        if(progressDialog == null){
            progressDialog = new ProgressDialog(mContext);
        }

        if(crossBorderUserMessage != null){
            id = crossBorderUserMessage.customsClearanceId;
            if (crossBorderUserMessage.isDefault){
                is_default = "1";
            }else {
                is_default = "0";
            }

            switchButton.setChecked("1".equals(is_default));
            reload_layout.setVisibility(View.VISIBLE);
            id_image_layout.setVisibility(View.GONE);
            name.setText(crossBorderUserMessage.realName);
            card_id.setText(crossBorderUserMessage.identityCardNumber);
            name.setFocusable(false);
            name.setFocusableInTouchMode(false);
            card_id.setFocusable(false);
            card_id.setFocusableInTouchMode(false);
        }else{
            reload_layout.setVisibility(View.GONE);
            id_image_layout.setVisibility(View.VISIBLE);
        }
    }

    private void addListener() {

        InputFilter inputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                if (charSequence.equals(" "))
                    return "";
                return null;
            }
        };

        card_id.addTextChangedListener(this);
        name.addTextChangedListener(this);
        card_id.setFilters(new InputFilter[]{inputFilter});
        card_id.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] aa = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
                return aa;
            }

            @Override
            protected char[] getReplacement() {
                char[] cc = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
                return cc;
            }
        });

        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if(isChecked){
                    is_default = "1";
                }else {
                    is_default = "0";
                }
            }
        });

    }


    int img_flag = 0;//0 正面 1 反面
    @OnClick({R.id.next,R.id.id_img0,R.id.id_img1,R.id.reload})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.next:
                if(TextUtils.isEmpty(name.getText().toString().trim())){
                    showToast("姓名不可为空");
                    return;
                }
                if(TextUtils.isEmpty(card_id.getText().toString().trim())){
                    showToast("身份证号码不可为空");
                    return;
                }
                progressDialog.show();
                mPresenter.cross_border_manage(id,is_default,name.getText().toString().trim(),card_id.getText().toString().trim(),img_url0,img_url1);
                break;
            case R.id.id_img0:
                img_flag = 0;
                Configuration.setCardType(this, 1);
                show_photo_dialog();
                break;
            case R.id.id_img1:
                img_flag = 1;
                Configuration.setCardType(this, 2);
                show_photo_dialog();
                break;
            case R.id.reload:
                name.setFocusable(true);
                name.setFocusableInTouchMode(true);
                card_id.setFocusable(true);
                card_id.setFocusableInTouchMode(true);
                reload_layout.setVisibility(View.GONE);
                id_image_layout.setVisibility(View.VISIBLE);
                break;
        }
    }


    CashTakePhotoDialog photoDialog;
    private void show_photo_dialog() {
        if(photoDialog == null){
            photoDialog = new CashTakePhotoDialog(mContext);
            photoDialog.setOnChooseListerner(new CashTakePhotoDialog.OnChooseListerner() {
                @Override
                public void cancel() {
                    photoDialog.dismiss();
                }

                @Override
                public void take_photo() {
                    photoDialog.dismiss();
                    rxPermissions
                            .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            if (aBoolean) {
//                                Intent intent = new Intent(mContext, ImageGridActivity.class);
//                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
//                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                //2、请求授权信息
                                startGetLicense();
                            } else {
                                Toast.makeText(mContext, "文件权限或照相机权限申请失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                @Override
                public void select_photo() {
                    photoDialog.dismiss();
                    Intent intent = new Intent(mContext, ImageGridActivity.class);
                    startActivityForResult(intent, IMAGE_PICKER);
                }
            });
        }
        photoDialog.show();
    }

    IDCardQualityLicenseManager mIdCardLicenseManager;
    public void startGetLicense() {
        mIdCardLicenseManager = new IDCardQualityLicenseManager(
                UploadCrossBorderNameActivity.this);

        long status = 0;
        try {
            status = mIdCardLicenseManager.checkCachedLicense();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (status > 0) {//大于0，已授权或者授权未过期
            Intent intent = new Intent(UploadCrossBorderNameActivity.this, IDCardDetectActivity.class);
            UploadCrossBorderNameActivity.this.startActivityForResult(intent, INTO_IDCARDSCAN_PAGE);
            //Toast.makeText(UploadIDsActivity.this, "授权成功", Toast.LENGTH_SHORT).show();

        } else { //需要重新授权
            Toast.makeText(UploadCrossBorderNameActivity.this, "没有缓存的授权信息，开始授权", Toast.LENGTH_SHORT).show();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        getLicense();
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            }).start();


        }

    }

    private void getLicense() {
        Manager manager = new Manager(UploadCrossBorderNameActivity.this);
        manager.registerLicenseManager(mIdCardLicenseManager);

        String uuid = Configuration.getUUID(UploadCrossBorderNameActivity.this);
        String authMsg = mIdCardLicenseManager.getContext(uuid);
        manager.takeLicenseFromNetwork(authMsg);
        if (mIdCardLicenseManager.checkCachedLicense() > 0) {//大于0，已授权或者授权未过期
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(UploadCrossBorderNameActivity.this, IDCardDetectActivity.class);
                    UploadCrossBorderNameActivity.this.startActivityForResult(intent, INTO_IDCARDSCAN_PAGE);
                    //Toast.makeText(UploadIDsActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        if(!TextUtils.isEmpty(name.getText().toString().trim()) && !TextUtils.isEmpty(card_id.getText().toString().trim())){
            next.setBackgroundResource(R.drawable.shape_round_f23051);
        }else{
            next.setBackgroundResource(R.drawable.bankcard_bind_unable_click_bkg);
        }

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                //uploadImg(images);
                    for (ImageItem item : images) {
                        File file = new File(item.path);
                        Luban.with(this)
                                .load(file)                                   // 传人要压缩的图片列表
                                //.ignoreBy(100)                                  // 忽略不压缩图片的大小
                                //.setTargetDir(getPath())                        // 设置压缩后文件存储位置
                                .setCompressListener(new OnCompressListener() { //设置回调
                                    @Override
                                    public void onStart() {
                                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        // TODO 压缩成功后调用，返回压缩后的图片文件
                                        Uri uri = Uri.fromFile(file);
                                        if(img_flag == 0){
                                            id_img0.setImageURI(uri);
                                            tag0.setVisibility(View.VISIBLE);
                                            re_front.setText("重新拍摄");
                                            mPresenter.customs_ocr(file,"1");
                                        }else{
                                            id_img1.setImageURI(uri);
                                            tag1.setVisibility(View.VISIBLE);
                                            re_back.setText("重新拍摄");
                                            mPresenter.customs_ocr(file,"2");
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // TODO 当压缩过程出现问题时调用
                                    }
                                }).launch();    //启动压缩
                    }
            } else if (data != null && requestCode == REQUEST_CODE_SELECT) {//拍照
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                //uploadImg(images);
            }
        }else if (requestCode == INTO_IDCARDSCAN_PAGE && resultCode == RESULT_OK) {
            byte[] iDCardImg = data.getByteArrayExtra("idcardimg_bitmap");
            if (iDCardImg != null) {
                Bitmap bmpIDCardImg = BitmapFactory.decodeByteArray(iDCardImg, 0, iDCardImg.length);
                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                if(img_flag == 0){
                    id_img0.setImageBitmap(bmpIDCardImg);
                    tag0.setVisibility(View.VISIBLE);
                    re_front.setText("重新拍摄");
                    take_photo_operate(bmpIDCardImg, path,1);
                }else{
                    id_img1.setImageBitmap(bmpIDCardImg);
                    tag1.setVisibility(View.VISIBLE);
                    re_back.setText("重新拍摄");
                    take_photo_operate(bmpIDCardImg, path,2);
                }
            }

        }
    }

    private void take_photo_operate(Bitmap bmpIDCardImg, String path,int type) {//type 1 正面照 2 反面照
        String name = "front_img.jpg";
        if(type == 2){
            name = "back_img.jpg";
        }
        saveImage(path,name,bmpIDCardImg);
        File file = new File(path,name);
        ArrayList<ImageItem> imageItems = new ArrayList<>();
        ImageItem imageItem = new ImageItem();
        imageItem.path = file.getAbsolutePath();
        imageItems.add(imageItem);
        if(type == 1){
            mPresenter.customs_ocr(file,"1");
        }else{
            mPresenter.customs_ocr(file,"2");
        }
    }

    public void saveImage(String path, String name,Bitmap bitmap){
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(path,name);
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
            bos.flush();
            bos.close();
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void customer_cross_border_list_success(CrossBorderListBean bean) {

    }

    @Override
    public void customer_cross_border_list_failed(String msg) {

    }

    @Override
    public void showDeleteSuccess() {

    }

    @Override
    public void showDeleteFailed() {

    }

    @Override
    public void changeDefaultSuccess() {

    }

    @Override
    public void changeDefaultfailed() {

    }

    @Override
    public void cross_border_manage_result(String sh_manage_state, String msg) {
        if(photoDialog != null){
            photoDialog.dismiss();
        }
        if(progressDialog != null){
            progressDialog.dismiss();
        }
        if(TextUtils.isEmpty(sh_manage_state)){
            showToast(msg);
        }else{
            showToast("保存成功");
            finish();
        }

    }

    @Override
    public void OnNewOcrResult(CustomerOcrBean bean) {
        if(bean != null){
            if(!TextUtils.isEmpty(bean.realName)){
                name.setText(bean.realName);
            }
            if(!TextUtils.isEmpty(bean.identityCardNumber)){
                card_id.setText(bean.identityCardNumber);
            }
            if(!TextUtils.isEmpty(bean.frontInfo)){
                img_url0 = bean.frontInfo;
            }
            if(!TextUtils.isEmpty(bean.backInfo)){
                img_url1 = bean.backInfo;
            }
        }
    }

    @Override
    public void OnNewOcrResultFail(String msg) {
        if(img_flag == 0){
            name.setText("");
            card_id.setText("");
        }
        showToast(msg);
    }
}
